package com.sinog.auth.config;

import com.sinog.auth.feign.UserLoginCheckService;
import com.sinog.core.util.JsonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * @desc 登录失败监听器
 * @author lj
 * @date -
 */
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    /**
     * 锁定时间
     */
    @Value("${gkzx.azbj.captcha.locktime}")
    private Integer captchaLockTime;
    @Value("${gkzx.azbj.captcha.singlelocktime}")
    private Integer singlelLockTime;
    /**
     * 锁定次数
     */
    @Value("${gkzx.azbj.captcha.locknum}")
    private Integer captchaLockNum;
    @Resource
    private UserLoginCheckService userLoginCheckService;

    /**
     * 描述
     * @param event event
     */
    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent event) {
        Object principal = event.getAuthentication().getPrincipal();
        Object details = event.getAuthentication().getDetails();
        String ip = ((WebAuthenticationDetails)details).getRemoteAddress();
        String userAccount = JsonUtil.toText(principal).replace("\"","");
        if(null != ((WebAuthenticationDetails)details).getSessionId()) {
            userLoginCheckService.lockUser(userAccount,captchaLockNum,captchaLockTime,singlelLockTime,ip);
        }
    }
}